package com.itheima.request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 解决中文乱码问题
 */

@WebServlet("/RequestDemo6")
public class RequestDemo6 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        /**
         * 解决post中文乱码问题
         */
        //设置request获取流对象的编码方式为UTF-8，要在获取流对象之前设置
//        request.setCharacterEncoding("utf-8");

        //tomcat会将所有的请求参数解析后存取map集合中
        Map<String, String[]> parameterMap = request.getParameterMap();

        //根据参数名获取某个参数（单个）
        String username = request.getParameter("username");
        System.out.println("解决乱码前:"+username);

        /**
         * 解决get请求中文乱码问题
         */
        //将得到的乱码中文数据使用iso-8859-1的字符集进行编码
//        byte[] bytes = username.getBytes(StandardCharsets.ISO_8859_1);
//        //将得到的字节数组使用UTF-8进行解码
//        username = new String(bytes, StandardCharsets.UTF_8);
//        System.out.println("解决乱码后："+username);
//        username=new String(username.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
        username = new String(username.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        System.out.println("解决乱码后："+username);
        //这种方式也可以解决post乱码



    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}